package com.qunar.train.mock.database;

import com.qunar.base.meerkat.dao.SqlHolder;
import com.qunar.base.meerkat.dao.UpdateDAO;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.Iterator;
import java.util.List;

/**
 * @author: xudong.tai
 * @since: 2018/6/26 Description:
 **/
public class MockUpdateDAO extends SqlSessionDaoSupport implements UpdateDAO {
    //接口返回值数据结构定义
    private int executeReturnValue;
    private int executeBatchReturnValue;

    //构造函数，初始化数据放在这里
    public MockUpdateDAO() {
    }

    public static ThreadLocal<MockUpdateDAO> threadLocal = new ThreadLocal<>();

    public static MockUpdateDAO getInstance() {
        if (threadLocal.get() == null) {
            threadLocal.set(new MockUpdateDAO());
        }
        return threadLocal.get();
    }


    //对外暴露set接口，可以个性化mock返回值
    public static void setExecuteReturnValue(int executeReturnValue) {
        getInstance().executeReturnValue = executeReturnValue;
    }

    public static void setExecuteBatchReturnValue(int executeBatchReturnValue) {
        getInstance().executeBatchReturnValue = executeBatchReturnValue;
    }

    //对接口函数进行实现，返回mock数据
    public int execute(String var1, Object var2) {
        this.getSqlSession().update(var1, var2);
        return getInstance().executeReturnValue;
    }

    public int executeBatch(List<SqlHolder> var1) {
        SqlSessionFactory sessionFactory = ((SqlSessionTemplate) super.getSqlSession()).getSqlSessionFactory();
        SqlSession sqlSession = sessionFactory.openSession(ExecutorType.BATCH, true);
        try {
            Iterator e = var1.iterator();
            while (e.hasNext()) {
                SqlHolder ex = (SqlHolder) e.next();
                sqlSession.update(ex.getSqlID(), ex.getBindParams());
            }
            sqlSession.commit();
        } catch (RuntimeException var19) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
        return getInstance().executeBatchReturnValue;
    }

    public static void clear() {
        getInstance().executeReturnValue = 0;
        getInstance().executeBatchReturnValue = 0;
    }
}
